package com.meixiang.activity.homes.service;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.CouponActivity;
import com.meixiang.activity.homes.shopping.CashierDeskActivity;
import com.meixiang.activity.homes.shopping.VerifyGoodsOrderActivity;
import com.meixiang.entity.OrderResult;
import com.meixiang.entity.account.UserInfo;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.util.GlideHelper;
import com.meixiang.view.TitleView;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 提交订单
 * author:xiejingwen
 */
public class SubmitOrdersActivity extends BaseActivity {
    @Bind(R.id.title)
    TitleView titleView;
    @Bind(R.id.tv_service_shop_title)
    TextView mTvServiceTitle;
    @Bind(R.id.iv_img)
    ImageView mIvImg;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.tv_money)
    TextView mTvMoney;
    @Bind(R.id.iv_subtract)
    ImageView mIvSubtract;
    @Bind(R.id.tv_order_number)
    TextView mTvNumber;
    @Bind(R.id.iv_plus)
    ImageView mIvPlus;
    @Bind(R.id.ll_appointment_serve_content)
    View mVContent;
    //    @Bind(R.id.tv_insurance)
//    TextView mTvInsurance;
//    @Bind(R.id.ll_insurance)
//    LinearLayout mLlInsurance;
    @Bind(R.id.tv_coupon)
    TextView mTvCoupon;
    @Bind(R.id.ll_coupon)
    LinearLayout mLlCoupon;
    @Bind(R.id.edt_message)
    EditText mEdtMessage;
/*    @Bind(R.id.tv_total)
    TextView mTvTotal;*/
    @Bind(R.id.tv_integral)
    TextView mTvIntegral;
    @Bind(R.id.cb_integral)
    CheckBox mCbIntegral;
    @Bind(R.id.btn_submit)
    Button mBtnSubmit;
    @Bind(R.id.ll_add)
    LinearLayout llAdd;
    private int number;
    private String temp;
    private String type;
    private String goodsId, price, goodsBody, goodsImage, trainingOrderId,isMainStore,point;
    private String beauticianId, date, time;
    private String cpId,cpPrice;
    private UserInfo mUserInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_submit_orders);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        number = Integer.parseInt(mTvNumber.getText().toString());
    }

    @Override
    protected void initTitle() {
        setTitle("提交订单");
    }

    @Override
    protected void initView() {
        MXApplication.mApp.AddActivity(this);
        //intent.putExtra("beauticianId",reservation.getList().get(mPosition).getBeauticianId());
        //  intent.putExtra("goodsId",getIntent().getStringExtra("goodsId"));
        type = getIntent().getStringExtra("type");
        goodsId = getIntent().getStringExtra("goodsId");//
        price = getIntent().getStringExtra("price");
        goodsBody = getIntent().getStringExtra("goodsBody");
        goodsImage = getIntent().getStringExtra("goodsImage");
        isMainStore = getIntent().getStringExtra("isMainStore");
        beauticianId = getIntent().getStringExtra("beauticianId");  //美容师ID 这是服务的
        date = getIntent().getStringExtra("date");  //美容师ID 这是服务的
        time = getIntent().getStringExtra("time");  //美容师ID 这是服务的

        mCbIntegral.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked){
                    if (null==mUserInfo||null==mUserInfo.getMemberConsumePoints()){
                        point="";
                    }else{
                        point=mUserInfo.getMemberConsumePoints();
                    }
                }else{
                    point="";
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MXApplication.mApp.hasLogin()){
            getUserinfo();
        }
    }
    private void getUserinfo() {

        HttpParams params = new HttpParams();
        HttpUtils.post(Config.USERINFO_URL, params, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

//                mRefresh.setRefreshing(false);
                //接口数据类型问题  暂不转换
                MXApplication.mApp.clearUser();
                mUserInfo = new Gson().fromJson(result.toString(), UserInfo.class);

                MXApplication.mApp.setUser(mUserInfo);

                if (null==mUserInfo||null==mUserInfo.getMemberConsumePoints()){
                    mTvIntegral.setText("可用0美积分");
                }else{
                    mTvIntegral.setText("可用"+mUserInfo.getMemberConsumePoints()+"美积分");
                }
            }

            @Override
            public void onError(String code, String message) {
//                mRefresh.setRefreshing(false);
                AbToastUtil.showToast(activity, message);
            }
        });
    }
    @Override
    protected void setData() {
        //title
        if (isMainStore!=null&&isMainStore.equals("1")){
            mTvServiceTitle.setText("总店服务");
        }else{
            mTvServiceTitle.setText("加盟店服务");
        }
        //隐藏加减按钮
        llAdd.setVisibility(View.GONE);

        if (!AbStrUtil.isEmpty(goodsBody)) {
            mTvTitle.setText(goodsBody);
        }
        if (!AbStrUtil.isEmpty(price)) {
            mTvMoney.setText("¥" + price);
            //mTvTotal.setText("¥" + price);
        }
        if (!AbStrUtil.isEmpty(goodsImage)) {
            GlideHelper.showImage(context, goodsImage, mIvImg);
        }

    }

    @OnClick({R.id.ll_coupon, R.id.btn_submit, R.id.iv_subtract, R.id.iv_plus, R.id.ll_appointment_serve_content})
    public void onClick(View view) {
        if (mUserInfo==null){
            AbToastUtil.showToast(context,"正在获取信息中...");
            getUserinfo();
            return;
        }
        switch (view.getId()) {
//            case R.id.ll_insurance:
//                startActivity(InsuranceSelectActivity.class);
//                break;
            case R.id.ll_coupon:
                Intent intent = new Intent(context, CouponActivity.class);
                intent.putExtra("fromCode", CouponActivity.CODE);
                intent.putExtra("goodsPrice", price);
                intent.putExtra("storeId",mUserInfo.getStoreId());
                startActivityForResult(intent, 0);
                break;
            case R.id.btn_submit:
                commitOrder();
                break;

            case R.id.iv_subtract:
                if (number > 1) {
                    mIvSubtract.setFocusable(true);
                    number--;
                    temp = String.valueOf(number);
                    mTvNumber.setText(temp);
                } else {
                    mIvSubtract.setFocusable(false);
                    mTvNumber.setText(temp);
                }
                /*double priceSub = Double.parseDouble(price);
                if (!AbStrUtil.isEmpty(price)) {
                    double sub = priceSub / number;
                    mTvTotal.setText(Tool.round(sub, 2).toString());
                }*/
                break;

            case R.id.iv_plus:
                if (number > 0 && number < 10) {
                    mIvPlus.setFocusable(true);
                    number++;
                    temp = String.valueOf(number);
                    mTvNumber.setText(temp);
                } else {
                    mIvPlus.setFocusable(false);
                    mTvNumber.setText(temp);
                }
               /* double pricePlus = Double.parseDouble(price);
                if (!AbStrUtil.isEmpty(price)) {
                    double plus = pricePlus * number;
                    mTvTotal.setText(Tool.round(plus, 2).toString());
                }*/
                break;
//            case R.id.tv_order_submission_view_order:
//                //查看订单详情
//                if(!AbStrUtil.isEmpty(type)&&(GlobalType.TRAIN_TYPE).equals(type)){
////                    //美容培训课程详情
//                    Intent intent1=new Intent(context, CosmeticTrainingCourseDetailActivity.class);
//                    if(!AbStrUtil.isEmpty(trainingOrderId)){
//                        intent1.putExtra("orderId",trainingOrderId);
//                    }else{
//                        Tool.showTextToast(context,"未获取到商品id");
//                        return;
//                    }
//                    startActivity(intent1);
//                    SubmitOrdersActivity.this.finish();
//                }
//                break;
//            case R.id.tv_order_submission_back_home:
//                //返回首页
//                for (Activity activity : AbActivityManager.getInstance().getActivityList()) {
//                    if(activity.getClass()!=MainActivity.class){
//                        activity.finish();
//                    }
//                }
//
//                break;
        }
    }

    private void commitOrder() {
        String url = Config.TRAINING_FOR_COMMIT_ORDER;
        Log.i("zys", "-----" + goodsId);
        /**
         * num 	String 	必填 			数量默认为1 必填
         remark 	String 	选填 			买家留言

         point 	String 	选填 			积分
         couponId 	String 	选填 			优惠券
         safeId 	String 	选填 			保险种类

         goodsId 	String 	必填 			商品ID
         time 	String 	必填 	10:00-11:30 		时间 这是服务的
         date 	String 	必填 	2016-04-03 		日期 这是服务的
         beauticianId 	String 	必填 			美容师ID 这是服务的
         */
        HttpParams params = new HttpParams();
        params.put("num", number + "");
        params.put("remark", mEdtMessage.getText().toString().trim());
        params.put("point", point);
        if (cpId!=null){
            params.put("couponId",cpId);
        }else{
            params.put("couponId", "");
        }
        params.put("safeId", "");
        if (!AbStrUtil.isEmpty(goodsId)) {
            params.put("goodsId", goodsId);
        }
        if (!AbStrUtil.isEmpty(type) && GlobalType.SERVICE_TYPE.equals(type)) {
            //服务
            params.put("time", time);
            params.put("date", date);
            params.put("beauticianId", beauticianId);
        }
        HttpUtils.post(url, params, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                OrderResult mOrderResult = AbJsonUtil.fromJson(result.toString(), OrderResult.class);
                Log.i("zys1", mOrderResult.getOrderId());
                Tool.showTextToast(context, message);
                Intent intent = new Intent(context, CashierDeskActivity.class);
                mOrderResult.setType(type);
                intent.putExtra(CashierDeskActivity.ORDER_RESULT, mOrderResult);
                intent.putExtra(CashierDeskActivity.PAYMENT_TYPE, CashierDeskActivity.ORDER_PAY);
                if (GlobalType.SERVICE_TYPE.equals(type)){
                    intent.putExtra(CashierDeskActivity.ORDER_TYPE,"FW");
                }else{
                    intent.putExtra(CashierDeskActivity.ORDER_TYPE,"PX");
                }
                HashMap<String, Class> map = new HashMap<>();
                map.put(CashierDeskActivity.GOTO_ACTIVITY, ServiceActivity.class);
                intent.putExtra(CashierDeskActivity.GOTO_ACTIVITY, map); // 支付成功之后跳转的activity
                startActivity(intent);
                finish();

            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context, message);
            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            cpId=data.getStringExtra(VerifyGoodsOrderActivity.CP_ID);
            cpPrice=data.getStringExtra(VerifyGoodsOrderActivity.CP_PRICE);
            if (cpId!=null&&cpPrice!=null){
                mTvCoupon.setText("已选择"+cpPrice+"元优惠券");
            }
        }
    }
}
